import axios from 'axios'

const http = axios.create({
    baseURL: 'http://114.215.186.216:3000', // 后端的请求地址
    timeout: 300000   // 请求超时时间
});




// 请求拦截器
http.interceptors.request.use(
    config => {
        const accessToken = localStorage.getItem('accessToken');
        if (accessToken) {
            config.headers['Authorization'] = `Bearer ${accessToken}`;
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
)
//刷新token
async function refreshToken() {
    const res = await http.post('/csy/refresh', {
        params: {
            token: localStorage.getItem('refreshToken')
        }
    })
    if (res.status == 200) {
        console.log(res);
        localStorage.setItem('accessToken', res.data.data.accessToken)
        localStorage.setItem('refreshToken', res.data.data.refreshToken)
    }
    return res
}




// 响应拦截器
http.interceptors.response.use(
    response => {
        return response;
    },
    async error => {
        const { config, status } = error.response
        if (status == 401) {
            const res = await refreshToken()
            if (res.status == 200) {
                return http(config)
            } else {
                alert('登录过期，请重新登录')
                return {}
            }
        }
        return Promise.reject(error);
    }
);

export default http;